package web.reports.action;

import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import common.JSONArray;
import domain.entities.*;
import org.apache.commons.math.stat.descriptive.rank.Percentile;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Namespace;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import org.springframework.beans.factory.annotation.Autowired;
import services.CompromisoPaisService;
import services.ProtocolCRUDService;
import services.ProtocoloCompromisopaisService;
import services.TherapeuticAreaCRUDService;
import services.exceptions.NoProtocoloCompromisopaisSelectedException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: Guillermo
 * Date: 07/12/12
 * Time: 13:03
 * To change this template use File | Settings | File Templates.
 */
@Namespace("/Reports/Scorecard")
public class ScorecardReportController extends ActionSupport  implements ServletResponseAware, ServletRequestAware {

    private HttpServletRequest request;
    private HttpServletResponse response;
    private CompromisoPaisService compromisoPaisService;
    private TherapeuticAreaCRUDService areaCRUDService;
    private ProtocoloCompromisopaisService protocoloCompromisopaisService;
    private List<Compromisopais> countries = new ArrayList<Compromisopais>();
    private List<TherapeuticArea> therapeuticAreas = new ArrayList<TherapeuticArea>();
    private Integer country;
    private Integer therapeuticArea;
    private String data;
    private List<ScorecardReports> list;

    @Autowired
    public ScorecardReportController(CompromisoPaisService compromisoPaisService, TherapeuticAreaCRUDService areaCRUDService, ProtocoloCompromisopaisService protocoloCompromisopaisService) {
        this.compromisoPaisService = compromisoPaisService;
        this.areaCRUDService = areaCRUDService;
        this.protocoloCompromisopaisService = protocoloCompromisopaisService;
    }

    @Action(value="main", results={
            @Result(name="success",location="/reports.scorecard.tiles", type="tiles")
    })
    public String execute() {

        countries =   compromisoPaisService.findAll();
        therapeuticAreas = areaCRUDService.list();
        return SUCCESS;
    }



    @Action(value="searchProtocols", results={
            @Result(name="success",location="/reports.scorecard.tiles", type="tiles")

    })
    public String searchProtocols() {

        try {
            StringBuffer stringBuffer = new StringBuffer();
            if( country!= null && !country.equals(0)){


            stringBuffer.append("[");

            list = protocoloCompromisopaisService.findScorecardForReports(country,therapeuticArea);

            for(ScorecardReports scorecardReports: list ){
                stringBuffer.append("['"+ scorecardReports.getMilestone() +"', " + scorecardReports.getDuration() + "]");
                stringBuffer.append(",");

                scorecardReports.setPercentile25(calculatePercentile(scorecardReports.getId(), 25));
                scorecardReports.setPercentile75(calculatePercentile(scorecardReports.getId(), 75));

            }
            stringBuffer.substring(0, stringBuffer.length() -1);
            stringBuffer.append("]");
            }else
                stringBuffer.append("error");
            data = stringBuffer.toString();


            countries =   compromisoPaisService.findAll();
            therapeuticAreas = areaCRUDService.list();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return SUCCESS;
    }


    private double calculatePercentile(Integer id, Integer percent){

        double retorno = 0;
       List<Integer> lista = protocoloCompromisopaisService.findDurationById(id);
        double[] durations = new double[lista.size()];
        int i =0;
        for(Integer duration : lista){
            if( !duration.equals(0)){
                durations[i] = duration;
                i++;
            }
        }

        Percentile percentile = new Percentile();
        if(durations.length > 0 )
            retorno = percentile.evaluate(durations, percent);


        return retorno;
    }



    @Override
    public void setServletRequest(javax.servlet.http.HttpServletRequest request) {
        this.request   = request;
    }

    @Override
    public void setServletResponse(javax.servlet.http.HttpServletResponse response) {
        this.response = response;
    }

    public List<Compromisopais> getCountries() {
        return countries;
    }

    public void setCountries(List<Compromisopais> countries) {
        this.countries = countries;
    }

    public List<TherapeuticArea> getTherapeuticAreas() {
        return therapeuticAreas;
    }

    public void setTherapeuticAreas(List<TherapeuticArea> therapeuticAreas) {
        this.therapeuticAreas = therapeuticAreas;
    }

    public Integer getCountry() {
        return country;
    }

    public void setCountry(Integer country) {
        this.country = country;
    }

    public Integer getTherapeuticArea() {
        return therapeuticArea;
    }

    public void setTherapeuticArea(Integer therapeuticArea) {
        this.therapeuticArea = therapeuticArea;
    }

    public String getData() {
        return data;
    }

    public void setData(String data) {
        this.data = data;
    }

    public List<ScorecardReports> getLista() {
        return list;
    }

    public void setLista(List<ScorecardReports> list) {
        this.list = list;
    }


}
